package com.vaadin.thomas.contenttool.data;

import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Relationship;
import org.neo4j.graphdb.Transaction;

public class Tag extends AbstractData implements Comparable<Tag> {

	protected Tag(Node n) {
		super(n);
	}

	static final String PROP_ID = "identifier";

	public String getValue() {
		return (String) node.getProperty(PROP_ID);
	}

	/**
	 * Retrieves (or creates a new) Tag.
	 */
	public static Tag get(String id) {

		Tag t = null;

		Node tags = Model.db
				.getReferenceNode()
				.getSingleRelationship(References.ROOT_TO_TAG,
						Direction.OUTGOING).getEndNode();

		for (Relationship r : tags.getRelationships(References.TAG_TO_TAGS)) {
			Node tag = r.getEndNode();
			String tagId = (String) tag.getProperty(PROP_ID);
			if (id.equals(tagId)) {
				t = new Tag(tag);
				break;
			}
		}

		if (t == null) {
			Transaction tx = Model.db.beginTx();

			try {
				Node n = Model.db.createNode();
				n.setProperty(PROP_ID, id);
				tags.createRelationshipTo(n, References.TAG_TO_TAGS);
				t = new Tag(n);

				tx.success();
			} catch (RuntimeException e) {
				tx.failure();
				throw e;
			} finally {
				tx.finish();
			}
		}

		return t;
	}

	@Override
	public int compareTo(Tag o) {
		return getValue().compareTo(o.getValue());
	}
}
